/**
 * This project create for studying propose at BUPT University. You can change or reuse this project anywhere
 */

package edu.bupt.ooad.library.ui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;

import net.miginfocom.swing.MigLayout;
import edu.bupt.ooad.library.Book;
import edu.bupt.ooad.library.BookDescription;
import edu.bupt.ooad.library.Library;

/**
 * @author Hamed Abdollahpour
 */
public class BooksPanel extends JPanel {

    private JComboBox categoryComboBox;

    private JTextField titleTextField;

    private JTextField authorTextField;

    private Library library;

    private JFormattedTextField isbnTextField;

    private JTable table;

    /**
     * Create the panel.
     */
    public BooksPanel(Library library) {
        this.library = library;

        setLayout(new BorderLayout());

        JPanel buttonPanel = new JPanel();
        add(buttonPanel, BorderLayout.SOUTH);
        buttonPanel.setLayout(new MigLayout("", "[][grow]", "[][][][][]"));

        JLabel label1 = new JLabel("Category:");
        buttonPanel.add(label1, "cell 0 0,alignx trailing");

        categoryComboBox = new JComboBox();
        categoryComboBox.setEditable(true);
        categoryComboBox.setModel(new DefaultComboBoxModel(new String[] {
                "", "Novel"
        }));
        buttonPanel.add(categoryComboBox, "cell 1 0,growx");

        JLabel label2 = new JLabel("Title:");
        buttonPanel.add(label2, "cell 0 1,alignx trailing");

        titleTextField = new JTextField();
        buttonPanel.add(titleTextField, "cell 1 1,growx");
        titleTextField.setColumns(10);

        JLabel label3 = new JLabel("Author:");
        buttonPanel.add(label3, "cell 0 2,alignx trailing");

        authorTextField = new JTextField();
        buttonPanel.add(authorTextField, "cell 1 2,growx");
        authorTextField.setColumns(10);

        JLabel label4 = new JLabel("ISBN:");
        buttonPanel.add(label4, "cell 0 3,alignx trailing");

        isbnTextField = new JFormattedTextField(NumberFormat.getInstance());
        buttonPanel.add(isbnTextField, "cell 1 3,growx");

        JButton searchButton = new JButton("Search");
        searchButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg) {
                search();
            }

        });
        buttonPanel.add(searchButton, "flowx,cell 1 4");

        JButton addButton = new JButton("Add");
        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg) {
                add();
            }
        });
        buttonPanel.add(addButton, "cell 1 4");

        JButton removeButton = new JButton("Remove");
        removeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg) {
                remove();
            }
        });
        buttonPanel.add(removeButton, "cell 1 4");

        table = new JTable();
        table.setModel(new BookTableModel(null));
        add(new JScrollPane(table), BorderLayout.CENTER);
    }

    private List<BookDescription> searchBook() {
        Object categoryObject = categoryComboBox.getSelectedItem();
        String isbnStirng = isbnTextField.getText();

        String category = categoryObject == null ? null : categoryObject.toString();
        String title = titleTextField.getText();
        String author = authorTextField.getText();
        int isbn = (isbnStirng != null && isbnStirng.length() > 0) ? Integer.parseInt(isbnStirng)
                : 0;

        List<BookDescription> descriptions = library.searchDescriptions(title, author, category,
                isbn);
        return descriptions;
    }

    private void search() {
        table.setModel(new BookTableModel(searchBook()));
    }

    private void add() {
        Object categoryObject = categoryComboBox.getSelectedItem();
        String isbnStirng = isbnTextField.getText();

        String category = categoryObject == null ? null : categoryObject.toString();
        String title = titleTextField.getText();
        String author = authorTextField.getText();
        int isbn = (isbnStirng != null && isbnStirng.length() > 0) ? Integer.parseInt(isbnStirng)
                : 0;

        // check for proper values
        if (category == null || category.trim().length() == 0) {
            JOptionPane.showMessageDialog(this, "Please enter valid category name", "error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (title == null || title.trim().length() == 0) {
            JOptionPane.showMessageDialog(this, "Please enter valid title name", "error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (author == null || author.trim().length() == 0) {
            JOptionPane.showMessageDialog(this, "Please enter valid author name", "error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (isbn == 0) {
            JOptionPane.showMessageDialog(this, "Please enter valid ISBN", "error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        int quantity = 0;
        String quantityString = JOptionPane.showInputDialog(this, "Please enter count of book");

        // cancel
        if (quantityString == null) {
            return;
        }

        try {
            quantity = Integer.parseInt(quantityString);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Invalid book count!");
            return;
        }

        if (quantity > 0) {
            BookDescription description = library.createDescriptions(title, author, category, isbn);
            List<Book> addedBooks = library.addBook(description, quantity);

            StringBuilder s = new StringBuilder();
            s.append("<html>");
            s.append("<p>").append(addedBooks.size())
                    .append(" Added to system. Added book serials</p><p>");

            for (Book book : addedBooks) {
                s.append(book.getBookId()).append(" ");
            }

            s.append("<p></html>");

            JOptionPane.showConfirmDialog(this, s.toString(), "Add", JOptionPane.PLAIN_MESSAGE);
        }

        // renew items
        search();
    }

    public void remove() {
        int[] selected = table.getSelectedRows();

        if (selected == null || selected.length == 0) {
            JOptionPane.showMessageDialog(this, "Please select books in tables first");
        } else {
            int result = JOptionPane.showConfirmDialog(this,
                    "Remove " + selected.length + " item?", "Question", JOptionPane.YES_NO_OPTION);

            if (result == JOptionPane.YES_OPTION) {
                BookTableModel model = (BookTableModel)table.getModel();
                for (int i = selected.length - 1; i >= 0; i--) {
                    int row = selected[i];
                    Book book = model.getBook(row);
                    BookDescription description = book.getDescription();

                    description.removeBook(book);
                    model.removeRow(row);
                }
            }
        }
    }

    /*
     * public void remove() { int result = JOptionPane.showConfirmDialog(this,
     * "All match data will be removed!", "Question",
     * JOptionPane.YES_NO_OPTION); if(result == JOptionPane.YES_OPTION) { Object
     * categoryObject = categoryComboBox.getSelectedItem(); String isbnStirng =
     * isbnTextField.getText(); String category = categoryObject == null ? null
     * : categoryObject.toString(); String title = titleTextField.getText();
     * String author = authorTextField.getText(); int isbn = (isbnStirng != null
     * && isbnStirng.length() > 0) ? Integer.parseInt(isbnStirng) : 0; String
     * serialString = JOptionPane.showInputDialog(this,
     * "Enter book ID (Empty for all mached books)"); int id = 0; try { id =
     * Integer.parseInt(serialString); } catch (Exception e) { // ignore }
     * List<BookDescription> descriptions = library.searchDescriptions(title,
     * author, category, isbn); for(BookDescription description:descriptions) {
     * List<Book> books = description.getBooks(); for(int i = books.size() - 1;
     * i >= 0; i --) { if(id == 0 || books.get(i).getBookId() == id) {
     * books.remove(i); } } } } }
     */

}
